import { ref, onUnmounted } from "vue";
import { useIntersectionObserver, useIntervalFn } from "@vueuse/core";

// 组件数据懒加载
export function useLazyData(apifn: () => void) {
  const target = ref(null);
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        stop();
        apifn();
      }
    },
    {
      threshold: 0,
    }
  );
  return target;
}
// 封装倒计时
export function useCountDeng(count: number = 60) {
  const time = ref(0); // 倒计时的秒数
  // vue定时器
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--;
      if (time.value <= 0) {
        pause(); // 暂停
      }
    },
    1000,
    {
      immediate: false,
    }
  );

  // 组件销毁时清除定时器
  onUnmounted(() => {
    pause();
  });

  // 封装函数 初始化倒计时和开启定时器
  const start = () => {
    // 初始化倒计时秒数
    time.value = count;
    // 开启定时器
    resume();
  };
  return {
    time,
    start,
  };
}
